package com.service.impl;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;

import com.service.CopyOfMsgPlueService;
import com.service.Service;

public class CopyOfMsgPlueServiceImpl implements CopyOfMsgPlueService,ApplicationContextAware {
	private final static Logger _log = Logger.getLogger(CopyOfMsgPlueServiceImpl.class);
	public void setApplicationContext(ApplicationContext applicationContext) {
		// TODO Auto-generated method stub
	}

	public void addBeanService(Service service) {
		// TODO Auto-generated method stub
		if (!applicationContext.containsBean(service.getServiceName())) {
			Class<?> serviceClass = getServiceClass(service.getClass().getName());
			BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(serviceClass);
			beanDefinitionBuilder.addPropertyValue("servicename", service.getServiceName());
			registerBean(service.getServiceName(), beanDefinitionBuilder.getRawBeanDefinition());
		}
		
	}

	public Class<?> getServiceClass(String className) {
		// TODO Auto-generated method stub
		try {
            return Thread.currentThread().getContextClassLoader().loadClass(className);
        } catch (ClassNotFoundException e) {
            _log.error("not found service class:" + className, e);
        }
		return null;
	}

	public void registerBean(String beanName, BeanDefinition beanDefinition) {
		// TODO Auto-generated method stub
		ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) applicationContext;
        BeanDefinitionRegistry beanDefinitonRegistry = (BeanDefinitionRegistry) configurableApplicationContext
                .getBeanFactory();
        beanDefinitonRegistry.registerBeanDefinition(beanName, beanDefinition);
	}

}
